package com.my.socket;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;

/**
 * @author: marshal
 * @date: 2021-12-30 2:29 PM
 */
public class KnockKnockClient {
    public static void main(String[] args) throws IOException {
        String hostName = "localhost";
        int portNumber = 4444;
        if (args != null && args.length > 0) {
            hostName = args[0];
            portNumber = Integer.parseInt(args[1]);
        }

        try (
                var kkSocket = new Socket(hostName, portNumber);
                var out = new PrintWriter(kkSocket.getOutputStream(), true);
                var in = new BufferedReader(new InputStreamReader(kkSocket.getInputStream()));
        ) {
            BufferedReader stdIn =
                    new BufferedReader(new InputStreamReader(System.in));
            String fromServer;
            String fromUser;

            while ((fromServer = in.readLine()) != null) {
                System.out.println("Server: " + fromServer);
                if (fromServer.equals("Bye.")) {
                    break;
                }
                fromUser = stdIn.readLine();
                if (fromUser != null) {
                    System.out.println("Client: " + fromUser);
                    out.println(fromUser);
                }
            }
        } catch (UnknownHostException e) {
            System.err.println("Don't know about host " + hostName);
            System.exit(1);
        } catch (IOException e) {
            System.err.println("Couldn't get I/O for the connection to " +
                    hostName);
            System.exit(1);
        }
    }
}
